package cn.net.xyan.pay.core.support

import cn.net.xyan.kotlin.logger
import cn.net.xyan.pay.core.entity.VendorUserInfo
import cn.net.xyan.pay.core.service.VendorUserInfoProvider
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.core.MethodParameter
import org.springframework.web.bind.support.WebDataBinderFactory
import org.springframework.web.context.request.NativeWebRequest
import org.springframework.web.method.support.HandlerMethodArgumentResolver
import org.springframework.web.method.support.ModelAndViewContainer

/**
 * Created by zarra on 2017/4/18.
 */

open class VendorUserInfoHandlerMethodArgumentResolver: HandlerMethodArgumentResolver {

    @Autowired
    open lateinit var vendorUserInfoProviders:List<VendorUserInfoProvider>

    override fun supportsParameter(methodParameter: MethodParameter?): Boolean {
        val result =  methodParameter!!.parameterType.equals( VendorUserInfo::class.java)

        logger.info("VendorUserInfoHandlerMethodArgumentResolver result:$result")

        logger.info("VendorUserInfoHandlerMethodArgumentResolver !!!!!!!!!")
        logger.info("VendorUserInfoHandlerMethodArgumentResolver !!!!!!!!!")
        logger.info("VendorUserInfoHandlerMethodArgumentResolver !!!!!!!!!")
        logger.info("VendorUserInfoHandlerMethodArgumentResolver !!!!!!!!!")

        return result
    }

    override fun resolveArgument(parameter: MethodParameter?, mavContainer: ModelAndViewContainer?, webRequest: NativeWebRequest?, binderFactory: WebDataBinderFactory?): Any {
        val vendor = webRequest!!.getParameter("vendor")

        logger.info("resolveArgument vendor:$vendor")

        val provider = vendorUserInfoProviders.first { it.vendor() == vendor }

        if (provider!=null){
            return provider.queryVendorUser(webRequest)
        }

        throw NullPointerException()

    }

}